package com.fable.ntzw_ga.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.fable.common.constants.OutExcelConstant;
import com.fable.common.dto.LandBuildPlanningDTO;
import com.fable.common.dto.LandUsePlanningDTO;
import com.fable.common.dto.MoreSheetExcelDTO;
import com.fable.common.handler.ExcelWriteHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author : guozhenhu
 * @date: 2023/7/21
 * @Description : 导出excel数据管理
 **/
@Slf4j
@Api(tags = "导出excel数据管理")
@RestController
@RequestMapping("/exportExcel")
public class ExportExcelController {

    @ApiOperation("单个Excel")
    @PostMapping(value = "/outputLandUsePlanningExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void outputLandUsePlanningExcel(HttpServletResponse response, @RequestBody List<LandUsePlanningDTO> dtoList) {
        //获取实体类属性的个数
        int lostCal = LandUsePlanningDTO.class.getDeclaredFields().length;
        //设置序号
        for (int i = 1; i <= dtoList.size(); i++) {
            dtoList.get(i - 1).setNumber(i + "");
        }
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String excelName = URLEncoder.encode("testExcel", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + OutExcelConstant.XLSX);
            //头策略使用默认
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            setTitleType(OutExcelConstant.ATTACHED_TABLE_1, OutExcelConstant.LAND_USE_PLANNING, OutExcelConstant.UNIT_1, lostCal);
            EasyExcel.write(response.getOutputStream(), LandUsePlanningDTO.class)
                    //设置拦截器或自定义样式
                    .registerWriteHandler(new ExcelWriteHandler())
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, cellStyle()))
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动设置列宽
                    .sheet(OutExcelConstant.ANNEX_1)
                    //设置默认样式及写入头信息开始的行数
                    .useDefaultStyle(true).relativeHeadRowIndex(3)
                    .doWrite(dtoList);
        } catch (IOException e) {
            log.error("导出错误", e);
        }

    }

    @ApiOperation("多个sheet页导出Excel")
    @PostMapping(value = "/moreSheetExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void outputProceduresPlanningExcel(HttpServletResponse response, @RequestBody MoreSheetExcelDTO testExcel) {
        //获取实体类属性的个数
        int lostCal1 = LandUsePlanningDTO.class.getDeclaredFields().length;
        //设置序号
        for (int i = 1; i <= testExcel.getDtoList1().size(); i++) {
            testExcel.getDtoList1().get(i - 1).setNumber(i + "");
        }
        int lostCal2 = LandBuildPlanningDTO.class.getDeclaredFields().length;
        //设置序号
        for (int i = 1; i <= testExcel.getDtoList2().size(); i++) {
            testExcel.getDtoList2().get(i - 1).setNumber(i + "");
        }
        //头策略使用默认
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("testExcelOutput", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            ExcelWriter build = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet sheet0 = EasyExcel.writerSheet(0, "附件1")
                    .head(LandUsePlanningDTO.class)
                    .useDefaultStyle(true)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, cellStyle()))
//                    .registerWriteHandler(new ExcelWriteHandler1())
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动设置列宽
                    .relativeHeadRowIndex(3)
                    .build();
            build.write(testExcel.getDtoList1(), sheet0);
            WriteSheet sheet1 = EasyExcel.writerSheet(1, "附件2")
                    .head(LandBuildPlanningDTO.class)
                    .useDefaultStyle(true)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, cellStyle()))
//                    .registerWriteHandler(new ExcelWriteHandler2())
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动设置列宽
                    .relativeHeadRowIndex(3).build();
            build.write(testExcel.getDtoList2(), sheet1);
            build.finish();
            response.flushBuffer();

        } catch (
                IOException e) {
            log.error("导出错误", e);
        }

    }

    /**
     * 表头数据
     */
    public void setTitleType(String attachedName, String excelName, String unit, int lostCal) {
        ExcelWriteHandler.setAttachedName(attachedName);//附表
        ExcelWriteHandler.setQianXinan(OutExcelConstant.QIANXINAN_PREFECTURE);//黔西南州
        ExcelWriteHandler.setExcelName(excelName);//excel表名
        ExcelWriteHandler.setFormFillingUnit(OutExcelConstant.FORM_FILLING_UNIT);//填表单位
        ExcelWriteHandler.setPreparer(OutExcelConstant.PREPARER);//填表人
        ExcelWriteHandler.setContactNumber(OutExcelConstant.CONTACT_NUMBER);//联系电话
        ExcelWriteHandler.setUnit(unit);//单位
        ExcelWriteHandler.setLostCal(lostCal);//列数

    }

    /**
     * 表头数据
     */
//    public void setTitleType1(String attachedName, String excelName, String unit, int lostCal) {
//        ExcelWriteHandler1.setAttachedName(attachedName);//附表
//        ExcelWriteHandler1.setQianXinan(OutExcelConstant.QIANXINAN_PREFECTURE);//黔西南州
//        ExcelWriteHandler1.setExcelName(excelName);//excel表名
//        ExcelWriteHandler1.setFormFillingUnit(OutExcelConstant.FORM_FILLING_UNIT);//填表单位
//        ExcelWriteHandler1.setPreparer(OutExcelConstant.PREPARER);//填表人
//        ExcelWriteHandler1.setContactNumber(OutExcelConstant.CONTACT_NUMBER);//联系电话
//        ExcelWriteHandler1.setUnit(unit);//单位
//        ExcelWriteHandler1.setLostCal(lostCal);//列数
//
//    }

    /**
     * @return 内容样式
     */
    public WriteCellStyle cellStyle() {
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }

}

